//
//  CustomView.swift
//  Maze24
//
//  Created by Mars on 2021/1/14.
//

import SwiftUI

struct CustomView: View {
  @Environment(\.presentationMode) var presentation
  
  @ObservedObject var model: Model
  
//  @Binding var buttons: [ButtonItem]
  
  @State var nums: [String] = ["", "", "", ""]
  @State var isInvalidNumber: Bool = false
  
  var body: some View {
    VStack {
      Text("输入要计算的四个数字")
        .font(.title2)
        .fontWeight(.semibold)
      
      buildInputGrid()
      
      Button("确定") {
        updateNumbers()
      }
      
      Text("输入的数字无法计算出 24 喔 :(")
        .foregroundColor(isInvalidNumber ? Color.red : Color.clear)
    }
  }
  
  func updateNumbers() {
    let arr: [Int] = nums.map {
      if let d = Int($0) {
        return d
      }
      else {
        return 0
      }
    }
    
    if Model().judgeTarget(arr) {
      var i = 0
      
      model.buttons = arr.map {
        defer { i += 1 }
        return ButtonItem(index: i, category: .number($0))
      }
      model.question = arr
      
      isInvalidNumber = false
      self.presentation.wrappedValue.dismiss()
    }
    else {
      isInvalidNumber = true
    }
  }
  
  func buildInputGrid() -> some View {
    VStack {
      HStack {
        buildInput(text: $nums[0])
        buildInput(text: $nums[1])
      }
      
      HStack {
        buildInput(text: $nums[2])
        buildInput(text: $nums[3])
      }
    }
    .padding(40)
  }
  
  func buildInput(text: Binding<String>) -> some View {
    TextField("", text: text)
      .keyboardType(.numberPad)
      .foregroundColor(Color.purple)
      .font(Font.system(size: 52, design: .monospaced).weight(.semibold))
      .textFieldStyle(RoundedBorderTextFieldStyle())
      .lineLimit(1)
      .minimumScaleFactor(0.8)
      .multilineTextAlignment(.center)
      .overlay(RoundedRectangle(cornerRadius: 9).stroke(Color.purple, lineWidth: 2))
  }
}

//struct CustomView_Previews: PreviewProvider {
//    static var previews: some View {
//        CustomView()
//    }
//}
